<template>
    <div>
        <pup-login :timeScend="timeScend" :isShow="isShowPup" v-if="type.includes('pup')" @submit="login"
            @getCode="getMsgCode" @close="closePup" @rememberPwd="rememberPwd" :rememberInfo="form" @signUp="signUp" @forgetPwd="forgetPwd"></pup-login>
        <right-login :timeScend="timeScend" v-if="type.includes('right')" @submit="login" @getCode="getMsgCode"
            @rememberPwd="rememberPwd" :rememberInfo="form" @signUp="signUp" @forgetPwd="forgetPwd"></right-login>
        <phone-login :title="title" :timeScend="timeScend" :isShow="isShowPhone" v-if="type.includes('phone')"
            @submit="login" @getCode="getMsgCode" @close="closePup" @rememberPwd="rememberPwd"
            :rememberInfo="form" @signUp="signUp" @forgetPwd="forgetPwd"></phone-login>
    </div>
</template>
<script>
import PupLogin from './pup-login.vue'
import RightLogin from './right-login.vue'
import PhoneLogin from './phone-login.vue'
import { showToast, setCookie, ua, removeCookie, getCookies } from '../../utils/index';
import { ACEencrypt, ACEdecrypt } from '../../utils/crypto';
import request from '~/request/request';
export default {
    name: 'login',
    components: {
        PupLogin,
        RightLogin,
        PhoneLogin
    },
    props: {
        /**显示类型
         * pup: 弹窗登录
         * right: 右侧登录
         * phone: 手机登录
         * */
        type: {
            type: Array,
            default: ['right', 'pup', 'phone']
        },
        title: {
            type: String,
            default: '个人博客'
        }
    },
    data() {
        return {
            isRemember: false, // 是否记住密码
            msgCode: '', // 邮箱验证码
            isShowPup: false, // 是否显示弹窗登录
            isShowPhone: false, // 是否显示手机登录
            timeScend: 60, // 验证码倒计时
            timer: null, // 定时器
            form: {
                username: '',
                password: '',
                code: ''
            }
        }
    },
    mounted() {
        ACEdecrypt({
            word: getCookies('rememberUser') || '',
            type: 'object',
            success: (Edecrypt) => {
                if (!Edecrypt.username || !Edecrypt.password) return;
                this.form.username = Edecrypt.username;
                this.form.password = Edecrypt.password;
                this.isRemember = true;
            }
        })
    },
    methods: {
        /**获取记住密码*/
        getRememberPwd() {
            ACEdecrypt({
                word: getCookies('rememberUser') || '',
                type: 'object',
                success: (Edecrypt) => {
                    if (!Edecrypt.username || !Edecrypt.password) return;
                    this.userName = Edecrypt.username;
                    this.password = Edecrypt.password;
                    this.isRemember = true;
                }
            })
        },
        /**登录*/
        login(e) {
            ACEencrypt({
                word: JSON.stringify(e),
                success: (Eencrypt) => {
                    request({
                        url: '/api/users/webLogin',
                        method: 'POST',
                        data: {
                            userLogin: Eencrypt,
                            ua: JSON.stringify(ua())
                        }
                    }).then(res => {
                        this.isShowPup = false;
                        this.isShowPhone = false;
                        if (res.code === 200) {
                            showToast({
                                msg: '登录成功',
                                type: 'success'
                            });
                            setCookie({
                                key: 'token',
                                value: res.data.token,
                                expires: 7
                            });
                            setCookie({
                                key: 'userInfo',
                                value: JSON.stringify(res.data),
                                expires: 7
                            });
                            if(this.$route.query.path){
                                window.location.href = this.$route.query.path
                            }
                            this.$emit('loginSuccess', res.data);
                        } else {
                            showToast({
                                msg: res.message || '登录失败',
                                type: 'error'
                            });
                        }
                    }).catch(err => {
                        showToast({
                            msg: err.message || '登录失败',
                            type: 'error'
                        });
                    })
                },
            })

        },
        /**获取邮箱验证码*/
        getMsgCode(username) {
            if (!username) return showToast({ msg: '请输入邮箱', type: 'error' });
            if (this.timer) return;
            request(`/api/email/getCodeByEmail?email=${username}`).then(res => {
                if (res.code === 200) {
                    this.timer = setInterval(() => {
                        if (this.timeScend <= 0) {
                            clearInterval(this.timer);
                            this.timer = null;
                            this.timeScend = 60;
                        } else {
                            this.timeScend--;
                        }
                    }, 1000)
                    showToast({
                        msg: '验证码已发送',
                        type: 'success'
                    });
                } else {
                    showToast({
                        msg: res.message || '验证码发送失败',
                        type: 'error'
                    });
                }
            }).catch(err => {
                showToast({
                    msg: err.message || '验证码发送失败',
                    type: 'error'
                });
            })
        },
        /**关闭弹窗*/
        closePup() {
            this.isShowPup = false;
            this.isShowPhone = false;
        },
        /**打开登录方法*/
        openLogin(type) {
            console.log("type ==>" ,type);
            if (type === 'pup') {
                this.isShowPup = true;
            } else if (type === 'phone') {
                this.isShowPhone = true;
            }
        },
        /**记住密码*/
        rememberPwd(isRemember, userInfo) {
            if (isRemember) {
                if (!userInfo.username || !userInfo.password) return showToast({ msg: '请输入用户名和密码', type: 'error' });
                ACEencrypt({
                    word: userInfo,
                    success: (Eencrypt) => {
                        setCookie({
                            key: 'rememberUser',
                            value: Eencrypt,
                            expires: 7
                        });
                    }
                })
                return;
            }
            removeCookie('rememberUser');
        },
        /**注册*/
        signUp() {
            this.$router.push('/signup');
        },
        /**忘记密码*/
        forgetPwd() {
            this.$router.push('/signup?type=reset');
        } 
    }

}
</script>
<style lang="scss" scoped></style>
